package moonhy.c2dm_client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import moonhy.c2dm_client.dw.ChatData;
import moonhy.c2dm_client.dw.ChatRoomData;
import moonhy.c2dm_client.dw.MemberData;
import moonhy.c2dm_client.dw.NoticeData;
import moonhy.c2dm_client.util.JSONSharedPreferences;
import moonhy.c2dm_client.util.httpConnectionManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ChatListActivity extends Activity{
	private SharedPreferences prefs;
	private OnSharedPreferenceChangeListener listener;
	private ArrayList<ChatRoomData> chatRoomJsonData = new ArrayList<ChatRoomData>();
	private ListView chatRoomListview;
	private chatRoomListAdapter roomlistAdapter;
	int open_room; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_room_list);
		
		Bundle extras = getIntent().getExtras();
		open_room = extras.getInt("frm_room_no", -1);
		
		
		if(open_room >= 0){
			Intent i = null;
			if(open_room == 0)
				i = new Intent(ChatListActivity.this, NoticeListActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			else if(open_room > 0)
				i = new Intent(ChatListActivity.this, ChatMainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			i.putExtra("frm_room_no", Integer.toString(open_room));
			startActivity(i);
		}
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		Editor edit = prefs.edit();
		edit.putInt("currentTab", 1).commit();
		
		
		
		
		
		
		
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(this, "gline", "chatRoomList");
			
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				ChatRoomData mList = new ChatRoomData(jsonObject.getInt("room_no"), jsonObject.getString("room_name"), jsonObject.getInt("alarm"), jsonObject.getString("bg"));
				chatRoomJsonData.add(mList);
				Log.d("C2DM", "Init Data: " + jsonObject.getInt("room_no"));
			}
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
		chatRoomListview = (ListView)findViewById(R.id.listviewChatList);
		roomlistAdapter = new chatRoomListAdapter(this, R.layout.chat_room_list_listview_layout, chatRoomJsonData);
		chatRoomListview.setAdapter(roomlistAdapter);
		
		new getChatRoomList(this).execute();
		
		
		
		chatRoomListview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//Log.d(TAG, "Clicked" + position);
				//view.setBackgroundColor(0x00);
				//chatListView.getChildAt(position).setBackgroundColor(0xFFFF0000);
				Log.d("C2DM", "ROOM NUMBER::::::: " + chatRoomJsonData.get(position).getRoomNo());
				
				int roomSeq = chatRoomJsonData.get(position).getRoomNo();
				
				Intent i;
				//if(roomSeq == 0)
				//	i = new Intent(ChatListActivity.this, NoticeListActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				//else{
					i = new Intent(ChatListActivity.this, ChatMainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					
					int totalChatCount	= prefs.getInt("UnreadCntTotal", 0);
					Editor edit = prefs.edit();
			        edit.putInt("UnreadCntTotal", totalChatCount - prefs.getInt("UnreadCnt"+roomSeq, 0));
			        edit.putInt("UnreadCnt"+roomSeq, 0);
			        
			        edit.commit();
				//}
				i.putExtra("frm_room_no", Integer.toString(roomSeq));
				startActivity(i);
            }
        });
		
		prefs.registerOnSharedPreferenceChangeListener(shared_listener);
		
		//prefs.registerOnSharedPreferenceChangeListener(listener);
	}
	
	public final SharedPreferences.OnSharedPreferenceChangeListener shared_listener = 
		new SharedPreferences.OnSharedPreferenceChangeListener(){
		@Override
		public void onSharedPreferenceChanged(SharedPreferences arg0, String key) {
			
			Log.i("C2DM", "[Chat Room List Event Fired] onSharedPreferenceChanged key: " + key);

			if (!key.equals("UnreadCntTotal") && (key.substring(0,9)).equals("UnreadCnt")) {
				
				for(int i = 0 ; i < chatRoomJsonData.size(); i++){

					
					if(chatRoomJsonData.get(i).getRoomNo() == Integer.parseInt(key.substring(9)) ){
						
						TextView tv	 = (TextView) chatRoomListview.getChildAt(i).findViewById(R.id.thisUnreadCount);
						TextView tv2 = (TextView) chatRoomListview.getChildAt(i).findViewById(R.id.thisLastMsg);
						
						int totCount = prefs.getInt("UnreadCnt"+key.substring(9), 0);
						if(totCount > 0){
							tv.setVisibility(View.VISIBLE);
							tv.setText("" + totCount);
						}else{
							tv.setVisibility(View.GONE);
						}
						
						JSONArray json_result;
	            		try {
	            			json_result = JSONSharedPreferences.loadJSONArray(getApplicationContext(), "glineChat", key.substring(9));
	            			if(json_result.length() > 0){
	            				JSONObject jsonObject = json_result.getJSONObject(json_result.length()-1);
	            				tv2.setText(jsonObject.getString("name") + ": " + jsonObject.getString("content"));
	            			}else{
	            				tv2.setText("");
	            			}
	            			
	            		} catch (JSONException e) {
	            			// TODO Auto-generated catch block
	            			e.printStackTrace();
	            		}
						
						Log.e("C2DM", "[Chat Room]   totCount::::: " + totCount + " --  "  + chatRoomJsonData.get(i).getRoomNo() + " -- " + Integer.parseInt(key.substring(9)));
						break;
					}
				}
			}
		}
	};
	
	/*
	@Override
	public void onRestart(){
		super.onStart();
		prefs.registerOnSharedPreferenceChangeListener(shared_listener);
		
		Log.e("C2DM", "onRestart");
		
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(this, "gline", "chatRoomList");
			chatRoomJsonData.clear();
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				ChatRoomData mList = new ChatRoomData(jsonObject.getInt("room_no"), jsonObject.getString("room_name"), jsonObject.getInt("alarm"));
				chatRoomJsonData.add(mList);
				Log.d("C2DM", "Init Data: " + jsonObject.getInt("room_no"));
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		roomlistAdapter.notifyDataSetChanged();
	}
	*/
	
	@Override
	public void onResume(){
		super.onResume();
		prefs.registerOnSharedPreferenceChangeListener(shared_listener);
		
		Log.e("C2DM", "OnResume");
		
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(this, "gline", "chatRoomList");
			
			chatRoomJsonData.clear();
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				ChatRoomData mList = new ChatRoomData(jsonObject.getInt("room_no"), jsonObject.getString("room_name"), jsonObject.getInt("alarm"), jsonObject.getString("bg"));
				chatRoomJsonData.add(mList);
				Log.d("C2DM", "Init Data on Resume: " + jsonObject.getInt("room_no"));
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		roomlistAdapter.notifyDataSetChanged();
	}
	
	@Override
	public void onStop(){
		super.onStop();
		prefs.unregisterOnSharedPreferenceChangeListener(shared_listener);
	}
	
	private class getChatRoomList extends AsyncTask<Void, Void, Void>{
		private Context context;
		
		private getChatRoomList(Context context){
			this.context = context;
		}

		@Override
		protected void onPreExecute(){
			//dialog.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			try {
				
				int memSeq = prefs.getInt("MEM_SEQ", -1);
				
				if(memSeq == -1){
					return null;
				}
				
				httpConnectionManager hcm = new httpConnectionManager(context);
				Map<String, String> map = new HashMap<String, String>();
				map.put("MEM_SEQ", Integer.toString(memSeq));

				JSONObject json = new JSONObject(hcm.readJSON_GET(getString(R.string.SERVER_URL) + "chat/chat_room_list.php", map));
				//JSONObject json_header = json.getJSONObject("header");
				JSONArray json_result = json.getJSONArray("data_result");
				
				chatRoomJsonData.clear();
				for (int i = 0; i < json_result.length(); i++) {
					JSONObject jsonObject = json_result.getJSONObject(i);
					
					ChatRoomData tmp_nd = new ChatRoomData();
					tmp_nd.setRoomNo(jsonObject.getInt("room_no"));
					tmp_nd.setRoomName(jsonObject.getString("room_name"));
					tmp_nd.setAlarm(jsonObject.getInt("alarm"));
					chatRoomJsonData.add(tmp_nd);
					Log.d("C2DM", "New Data: " + jsonObject.getInt("room_no"));
				}
				
				JSONSharedPreferences.remove(context, "gline", "chatRoomList");
				JSONSharedPreferences.saveJSONArray(context, "gline", "chatRoomList", json_result);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused)
        {
        	roomlistAdapter.notifyDataSetChanged();
        }
	}
	
	
	
	private class chatRoomListAdapter extends ArrayAdapter<ChatRoomData> {

        private ArrayList<ChatRoomData> items;
        
        
        public chatRoomListAdapter(Context context, int textViewResourceId, ArrayList<ChatRoomData> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.chat_room_list_listview_layout, null);
            }
            
            ChatRoomData p = items.get(position);
            
            
            ImageView alarmImg = (ImageView) v.findViewById(R.id.alarmImage);
			ImageView muteImg  = (ImageView) v.findViewById(R.id.muteImage);
            if(p.getAlarm() == 0){
				alarmImg.setVisibility(View.VISIBLE);
				muteImg.setVisibility(View.GONE);
			}else{
				alarmImg.setVisibility(View.GONE);
				muteImg.setVisibility(View.VISIBLE);
			}
            
            
            if (p != null) {
                TextView m1 = (TextView) v.findViewById(R.id.chatRoomName);
                TextView m2 = (TextView) v.findViewById(R.id.thisUnreadCount);
                TextView m3 = (TextView) v.findViewById(R.id.thisLastMsg);
                
                if(m1 != null)
                	m1.setText(p.getRoomName());
                if(m2 != null){
                	int totCount = prefs.getInt("UnreadCnt"+Integer.toString(p.getRoomNo()), 0);
					if(totCount > 0){
						m2.setVisibility(View.VISIBLE);
						m2.setText("" + totCount);
					}else{
						m2.setVisibility(View.GONE);
					}
                }
                if(m3 != null){
            		try {
            			JSONArray json_result = JSONSharedPreferences.loadJSONArray(getApplicationContext(), "glineChat", Integer.toString(p.getRoomNo()));
            			if(json_result.length() > 0){
            				JSONObject jsonObject = json_result.getJSONObject(json_result.length()-1);
            				m3.setText(jsonObject.getString("name") + ": " + jsonObject.getString("content"));
            			}else{
            				m3.setText("");
            			}
            		} catch (JSONException e) {
            			// TODO Auto-generated catch block
            			e.printStackTrace();
            		}
                }
            }
            return v;
        }
	}
}